function $(el){
    return document.querySelector(el)
}
let tab = $('.tab tbody'),
    ul = $('.page_box ul'),
    count = $('#count'),
    search = $('#search'),
    order = $('#order'),
    page_box = $('.page_box'),
    prev = $('#prev'),
    next = $('#next'),
    flag,
    list,
    cur;
search.addEventListener('input',(e)=>{
    redder(newData())
})
// 封装获取数据函数
function newData(){
    let data_s = [],
        val = search.value.trim();
    datas.map((obj)=>{
        if(obj.name.indexOf(val) === 0){
            data_s.push(obj)
        }
    })
    return data_s
}
// 封装渲染元素函数
function redder(data){
    data = data === undefined? datas : data;
    let countVal = count.value,
        orderVal = order.value,
        len = Math.ceil(data.length/countVal),
        li='',
        cur = $('.cur'),
        idx = [...ul.children].indexOf(cur),
        p,
        fn = (x,y) => {return x[orderVal] - y[orderVal]};
    if(orderVal === 'name'){
        fn = (x,y) => new Intl.Collator('zh-Hans-CN', { sensitivity: 'accent' }).compare(x.name, y.name);
    }
    data.sort(fn)
    if(len <= idx ) cur = null;
    p = cur === null? 0 : idx;
    tab.innerHTML  = data.slice(p*countVal,(p+1)*countVal).map((obj1)=>{
        return `<tr>
                    <th>${obj1.name}</th>
                    <th>${obj1.age}</th>
                    <th>${obj1.sorc}</th>
                    <th>${obj1.level}</th>
                </tr>`
    }).join('')
    for(i=0;i<len;i++){
        li+=`<li>${i+1}</li>`
    }
    ul.innerHTML = li;
    list = [...ul.children]
    list[p].classList.add('cur')
    page_box.classList.add('show')
}
redder()
// 分页器点击事件
ul.addEventListener('click',(e)=>{
    let target = e.target
    cur = $('.cur') 
    if(target.nodeName === 'LI'){
        cur&&cur.classList.remove('cur')
        target.classList.add('cur')
    }
    redder(newData())
})
//选择条数
count.addEventListener('change',(e)=>{
    redder(newData())
})
// 选择排序方式
order.addEventListener('change',(e)=>{
    redder(newData())
})
next.addEventListener('click',(e)=>{
    flag = true;
    changePage();
})
prev.addEventListener('click',(e)=>{
    flag = false;
    changePage();
})
// 封装上一页和下一页的点击函数
function changePage(){
    let  idx = list.indexOf($('.cur'))
    if( list.length=== 1) return;
    $('.cur').classList.remove('cur')
    flag ? idx++ : idx-- ;
    if(idx>list.length-1) idx = list.length-1;
    if(idx<0) idx = 0;
    list[idx].classList.add('cur');
    redder(newData());
}
